<!--
 * @description  : 案件-非法流通卷烟码段统计表
 * @descriptionDetail: 案件-非法流通卷烟码段统计表
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-08-27 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
      <view class="white-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
		<!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="main-content">
      <u-form :model="dataForm" :error-type="errorType" ref="uForm">
        <u-form-item label="当事人" :label-width="labelWidth" :required="true" prop="party">
          <u-input placeholder="请输入" :disabled="!state.canEdit" input-align="right" v-model="dataForm.party" />
        </u-form-item>
        <u-form-item label="案发日期" :label-width="labelWidth" :required="true" prop="findCaseDate" ref="findCaseDateChangeRef">
          <u-input placeholder="请输入" :disabled="true" input-align="right" v-model="dataForm.findCaseDate" @click="()=>{if(state.canEdit) showTime=true}" />
        </u-form-item>
        <u-form-item label="案发地点" :label-width="labelWidth" :required="true" prop="casePlace">
          <u-input placeholder="请输入" :disabled="!state.canEdit" input-align="right" v-model="dataForm.casePlace" />
        </u-form-item>
        <u-form-item label-position="top" label="执法人员及执法证号" :label-width="labelWidth" :required="true" prop="undertaker">
          <u-input placeholder="请选择执法人员" :disabled="true" input-align="right" v-model="dataForm.undertaker" @click="personSelect" />
        </u-form-item>
        <u-form-item label-width="200" label="当事人签名" label-position="left" prop="fileId">
          <view
            style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;"
            @click="showSignView"
          >
            <m-upload
              :uploadParam="{'fiGroupCode':'zmglpt-regie-zj-images'}"
              maxCount="1"
              :file-list="signImgList"
              uploadText="未签名"
              :showDefView="false"
              :deletable="state.canEdit"
              width="300rpx"
              height="150rpx"
              index="signImgList"
              :disabled="true"
              imageMode="aspectFit"
              @on-list-change="changeUpload"
            >
            </m-upload>
          </view>
          <signature :mustHor="true" :visible="isShowSignView" :disabled="!state.canEdit" @close="isShowSignView = false" @save="saveSign">
          </signature>
        </u-form-item>
        <u-form-item label-position="top" label="卷烟品牌及码段信息" :border-bottom="false">
          <view class="table">
            <u-table font-size="26">
              <u-tr class="u-tr">
                <u-th width="12%" class="u-th">
                  序号
                </u-th>
                <u-th class="u-th" width="40%">
                  品牌
                </u-th>
                <u-th class="u-th" width="40%">
                  前十六位码段
                </u-th>
                <u-th class="u-th" width="40%">
                  后十六位码段
                </u-th>
                <u-th class="u-th" width="16%">
                  数量(条)
                </u-th>
                <u-th class="u-th" width="26%">
                  最小单位数(支)
                </u-th>
                <u-th class="u-th" width="30%">
                  备注
                </u-th>
              </u-tr>
              <u-tr class="u-tr" v-for="(item,index) in dataForm.goods" :key="index">
                <u-td width="12%" class="u-td">
                  {{ index+1 }}
                </u-td>
                <u-td class="u-td" width="40%">
                  {{ item.goodsName|| '&nbsp;' }}
                </u-td>
                <u-td class="u-td" width="40%">
                  {{ item.firstSixteenNum|| '&nbsp;' }}
                </u-td>
                <u-td class="u-td" width="40%">
                  {{ item.lastSixteenNum|| '&nbsp;' }}
                </u-td>
                <u-td class="u-td" width="16%">
                  {{ item.qty||'&nbsp;' }}
                </u-td>
                <u-td class="u-td" width="26%">
                  {{ item.minQty|| '&nbsp;' }}
                </u-td>
                <u-td class="u-td" width="30%">
                  {{ item.remarks|| '&nbsp;' }}
                </u-td>
              </u-tr>
            </u-table>
          </view>
        </u-form-item>
      </u-form>
    </view>

    <view class="bottom-btn-info" v-if="state.canEdit">
      <u-row gutter="16">
        <u-col span="6">
          <u-button plain type="primary" @click="saveOrSubmit('save')">
            保存
          </u-button>
        </u-col>
        <u-col span="6">
          <u-button type="primary" @click="saveOrSubmit('submit')">
            提交
          </u-button>
        </u-col>
      </u-row>
    </view>
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <!-- 查案时间选择 -->
    <u-calendar :max-date="maxDate" mode="date" v-model="showTime" @change="changeDate('findCaseDate',$event)"></u-calendar>
  </view>
</template>
<script>
import officeService from "@/service/case/office.service.js";
import caseCommon from "../caseCommonMixin.js";
import PersonSelection from "@/pages/case/components/personSelection.vue";
import {dateUtils,} from "@/common/util";
import Signature from "@/components/signature";
import mUpload from '@/components/m-upload.vue';
import zjCommonService from "@/service/common/common.service";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			PersonSelection,
			Signature,
			mUpload,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				personSelectShow: false,
				isShowSignView: false,
				signImgList: [],
				showTime: false,
				maxDate: '2099-12-31',
				rules: {
					// 当事人
					party: [{
						required: true,
						message: '请填写当事人',
						trigger: ['change', 'blur', ],
					}, ],
					findCaseDate: [{
						required: true,
						message: '请选择查案时间',
						trigger: ['change', 'blur', ],
					}, ],
					casePlace: [{
						required: true,
						message: '请填写案发地点',
						trigger: ['change', 'blur', ],
					}, ],
					undertaker: [{
						required: true,
						message: '请选择执法人员',
						trigger: ['change', 'blur', ],
					}, ],
				},
				errorType: ['border-bottom', 'message', ],
				labelPosition: "top",
				labelWidth: '280',
				dataForm: {}, // 表单数据
				caseParam: {}, // 上个页面传过来的参数
				doc: {},
				psParam: {},
				// goodsListShow:true,
				titSty: {
					'fontSize': '32rpx',
					'marginLeft': '-15px',
				},
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}]
			}
		},

		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(preParams) {
			this.caseParam = this.getRouteParam();
			this.psParam.caseUuid = this.caseParam.caseUuid;
			// console.log('参数：' + JSON.stringify(this.caseParam));
		},
		watch: {
			showTime() {
				this.$refs.findCaseDateChangeRef.validation();
			},
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo;
				this.setRightBtns();
			});
			this.initDocData();
		},
		methods: {
			// 初始化数据
			initDocData() {
				officeService.getLawLessnessDoc(this.caseParam.id, this.caseParam.docUuid, this.caseParam.bizUuid).then((res) => {
					if (res.success) {
						let [tiInfo, rs, ] = [{}, {}, ];
						if (res.data.length === 2) {
							tiInfo = res.data[0];
							rs = res.data[1];
							Object.keys(tiInfo).forEach(key => {
								rs[key] = tiInfo[key];
							});
						} else {
							rs = res.data[0];
						}
						this.objMerge(this.dataForm, rs);
						if (!this.$u.test.isEmpty(this.dataForm.fileId)) {
							this.signImgList = [{
								gfiId: this.dataForm.fileId,
							}, ];
						}
					} else {
						this.$u.toast(res.msg);
					}
				})
			},
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			saveSign(v) {
				console.log(v);
				this.isShowSignView = false;
				this.$modal.showLoading('保存签名...');
				let uploadParam = {
					'fiGroupCode': 'zmglpt-regie-zj-images',
				};
				uploadParam.fileName = Date.now() + '.jpg';
				zjCommonService.uploadBase64ForApp(v, uploadParam).then(res => {
					this.$modal.hideLoading();
					if (res.success) {
						this.signImgList = [res.bean, ]
						this.dataForm.fileId = res.bean.gfiId;
					} else {
						console.log(res.msg);
						this.$u.toast('签名信息保存失败');
					}
				}).catch(er => {
					console.log(er);
					this.$modal.hideLoading();
					this.$u.toast('签名信息保存失败');
				});
			},
			// 上传/删除图片事件
			changeUpload(list, key) {
				if (key == 'signImgList') {
					if (list.length == 0) {
						this.dataForm.fileId = "";
						this.signImgList = []
					}
					return;
				}
			},
			showSignView() {
				if (!this.state.canEdit) return;
				this.isShowSignView = true;
			},
			// 查案时间选择
			changeDate(type, e) {
				this.dataForm[type] = dateUtils.dateFormat("yyyy年MM月dd日", new Date(e.result));
				this.$refs.findCaseDateChangeRef.validation();
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.saveOrSubmit('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			// 执法人员选择
			personSelect() {
				if (!this.state.canEdit) {
					return;
				}
				this.psParam = {
					min: 1,
					selectedPsrLst: [],
					caseUuid: this.caseParam.caseUuid,
				};
				this.personSelectShow = true;
			},
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				let employeeList = [...e, ];
				let tIds = [];
				let tNames = [];
				employeeList.forEach(el => {
					tIds.push(el.personUuid);
					tNames.push(el.personName + '(' + el.leCertNo + ')');
				});
				this.dataForm.undertakerUuids = tIds.join();
				this.dataForm.undertaker = tNames.join();
			},
			// 表单验证
			validForm() {
				let basicValid = false;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						basicValid = true;
						console.log('表单验证通过');
					} else {
						basicValid = false;
						console.log('表单验证失败');
					}
				});
				return basicValid;
			},
			saveOrSubmit(type) {
				// 点击提交、保存按钮
				let flag = this.validForm();
				if (flag) {
					this.submitDocInfo(type);
				}
			},
			// 保存/提交接口
			submitDocInfo(type) {
				let {
					docUuid,
					titemUuid,
				} = this.caseParam;
				type == 'save' && this.$u.loading('数据保存中...');
				this.dataForm.caseUuid = this.psParam.caseUuid;
				officeService.saveLawLessnessDoc(this.dataForm, docUuid, titemUuid).then(res => {
					this.$u.hideLoading();
					if (res.success) {
						this.dataForm = res.bean;
						try {
							if (!this.doc) this.doc = res.data[0];
						} catch (e) {
							console.log(e);
						}
						if (type == 'submit') {
							if (this.signImgList.length > 0) {
								this.$u.loading('数据提交中...');
								officeService.submitLawLessnessDoc(this.dataForm, docUuid, titemUuid).then(res => {
									this.$u.hideLoading();
									this.saveBehaviorLog(1, this.caseParam, this.doc);
									this.$u.toast(res.msg);
									if (res.success) {
										this.backPrev({
											paramKey: "offiList",
											param: {
												caseUuid: this.caseParam.bizUuid,
												caseCode: this.caseParam.caseCode,
												caseType: this.caseParam.caseType,
											},
										});
									}
								})
							} else {
								this.$modal.confirm('当事人未签名，是否继续提交?', () => {
									this.$u.loading('数据提交中...');
									officeService.submitLawLessnessDoc(this.dataForm, docUuid, titemUuid).then(res => {
										this.$u.hideLoading();
										this.saveBehaviorLog(1, this.caseParam, this.doc);
										this.$u.toast(res.msg);
										if (res.success) {
											this.backPrev({
												paramKey: "offiList",
												param: {
													caseUuid: this.caseParam.bizUuid,
													caseCode: this.caseParam.caseCode,
													caseType: this.caseParam.caseType,
												},
											});
										}
									})
								}, )
							}
						} else if (type == 'preview') {
							officeService.buildLocalPunish("/record/doc-lawlessness-cigar", this.doc.docInsUuid).then(pdfId => {
								if (pdfId.success) {
									this.downloadFile(pdfId.bean, "预览", false);
								} else {
									this.$u.toast(pdfId.msg);
								}
							});
						} else {
							this.saveBehaviorLog(0, this.caseParam, this.doc);
							this.$u.toast(res.msg);
						}
					} else {
						this.$u.hideLoading();
						this.$u.toast(res.msg);
					}
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	/deep/ .main-content .u-cell-item-box {
		margin-left: -15px;
	}

	.table {
		width: 100%;
		overflow-x: scroll;
	}

	/deep/.u-form-item--right__content {
		width: 100%;
	}

	/deep/ .u-form-item--right__content__slot {
		width: 100%;
	}

	.u-td {
		white-space: nowrap;
		overflow: hidden;
	}
</style>
